APP=mdown
CLASS=Markdown
OUT_PATH=build/js
OUT_FILE=$OUT_PATH/$APP.js
CC_FILE=$OUT_PATH/$APP.cc.js
NAMESPACE=md
EXPORT_SRC="function(s){return $NAMESPACE.$CLASS.instance.makeHtml(s)}"
EXPORT_DST=this"['$APP']"
TMP=tmp

RM_CLOSURES='
  s/$closure(\([^,]*\),"\([^"]*\)")/$closure(\1, \1.\2)/g ;
  s/^\tvar m = o\[f\];$/var m=f;/ ;
'

rm `find $OUT_PATH -type f | sed /\\.svn/d`

haxe -cp src -main $CLASS --js-namespace $NAMESPACE -js $OUT_FILE

# export our target and declare some vars
echo "$EXPORT_DST=(function(){var $NAMESPACE,\$_,\$Main,\$closure,\$estr,js;" > $TMP;

# turn calls to $closure function into normal function calls
# strip no-op lines containing "null;" or "else null;"
sed " /^[ \x09]*\(else \)\?null;$/d ;
      s/eval(js\.Boot\.__ns)/$NAMESPACE/g ;
    $RM_CLOSURES"  $OUT_FILE >> $TMP

# finish the closure
echo "return $EXPORT_SRC;}());" >> $TMP;

mv $TMP $OUT_FILE;

#google closure compiler
java -jar ../closure/compiler.jar \
--output_wrapper "(function(){%output%}());" \
--compilation_level ADVANCED_OPTIMIZATIONS \
< build/js/mdown.js > $CC_FILE

